package com.yunyv.iotudpserve.UDP.listener;

import com.alibaba.fastjson.JSONObject;
import com.yunyv.iotudpserve.UDP.dto.UDPBo;
import com.yunyv.iotudpserve.utils.HttpUtil;
import com.yunyv.iotudpserve.utils.StringUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/********************************************************************************
 ** author： zhangtianhe
 ** date：2024年05月22日 17:09
 ** description&desc：
 *********************************************************************************/
@WebListener
public class UDPListener implements ServletContextListener {
    public static final int MAX_UDP_DATA_SIZE = 4096;
    public static final int UDP_PORT = 65011;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        System.out.println("========UDPListener Initialized=========");
        try {
//　　　　　　　// 启动一个线程，监听UDP数据报
            new Thread(new UDPProcess(UDP_PORT)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class UDPProcess implements Runnable {
        DatagramSocket socket = null;

        public UDPProcess(final int port) throws SocketException {
            socket = new DatagramSocket(port);
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("=======UDPProcess======");
            while (true) {
                byte[] buffer = new byte[MAX_UDP_DATA_SIZE];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                try {
                    socket.receive(packet);
                    new Thread(new Process(packet)).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    class Process implements Runnable {

        public Process(DatagramPacket packet) throws UnsupportedEncodingException {
            // TODO Auto-generated constructor stub
            byte[] buffer = packet.getData();// 接收到的UDP信息，然后解码
            String srt1 = new String(buffer,"GBK").trim();
            String srt2 = new String(buffer, "UTF-8").trim();
            String srt3 = new String(buffer,"ISO-8859-1").trim();
            System.out.println("=======Process srt1 GBK======" + srt1);
            System.out.println("=======Process srt2 UTF-8======" + srt2);
            System.out.println("=======Process srt3 ISO-8859-1======" + srt3);

            List<UDPBo> udpBoList = jiexiIot(srt2);

            //http
            for (UDPBo udpBo:udpBoList){
                Map<String,String> header = new HashMap<String,String>();
                header.put("Content-Type", "application/json");
                //请求参数
                Map<String,Object> param = new HashMap<String,Object>();
                param.put("data",udpBo);
                String paramJson = JSONObject.toJSONString(param);

                String result =  HttpUtil.postJson("http://127.0.0.1:8086/httpPublish/send",header,paramJson);
            }
//            mqtt
//            udpBoList.stream().forEach(udpBo -> MQTTPublish.MQttSend(udpBo));
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("====Process run=====");
        }

    }

    public List<UDPBo> jiexiIot(String srt){
        List<UDPBo> boList  =new ArrayList<>();
        String deviceName="";//设备编号
        String deviceStatus="";//设备状态
        String devicesGsv="";//设备示值浓度
//        String srt = "#&868968072122089/003/4;MOD:WL136,0;GSV:1,30,%LEL,4;TPV:-20.5,C;PSV:323,Kpa,1;@8AAC";

//        String srt ="#&HBS030001001/001/3;DVS:1;GSV:1,0,%LEL,1;NTS:21,0;@74FE";
        String[] fruits = srt.split("/");
        for (int i=0;i<fruits.length;i++){
            if (i%3==0){//取设备编号
                deviceName =fruits[i];//设备编号
            }
            if(i%3==1){//设备状态
                deviceStatus=fruits[i];//设备状态
            }
            if (i%3==2){//设备示值浓度
                devicesGsv=fruits[i];
                if (StringUtils.isNotEmpty(fruits[i])){
                    if (Double.parseDouble(fruits[i])>100.00){//最大值为100
                        devicesGsv="100.00";//设备示值浓度
                    }
                }
                UDPBo udpBo=new UDPBo();
                udpBo.setDeviceStatus(deviceStatus);
                udpBo.setDeviceName(deviceName);
                udpBo.setDevicesGsv(devicesGsv);
                boList.add(udpBo);
            }
        }
        return boList;
    }
}
